package org.thattoolkit.srvctl;

import java.io.File;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import org.apache.commons.exec.OS;

public abstract class AbstractOperatingSystem implements OperatingSystem {
	private static OperatingSystem thisSystem = null;
	protected Properties props;
	
	public String getProperty(String prop) {
		return props.getProperty(prop);
	}

	static public OperatingSystem getSystem() {
		if(thisSystem == null) {
			if (OS.isFamilyUnix())
				thisSystem = new UnixOperatingSystem();
			else if (OS.isFamilyWindows()) {
				thisSystem = new WindowsOperatingSystem();
				((WindowsOperatingSystem)thisSystem).props.setProperty("extension", ".exe");
			}
			else if (OS.isFamilyMac())
				thisSystem = new MacOperatingSystem();
		}
		if(thisSystem == null)
			throw new RuntimeException("Unknown Operating System");
		return thisSystem;
	}

	public final String getName() {
		return System.getProperty("os.name");
	}

	public final String getArchitecture() {
		return System.getProperty("os.arch");
	}
	
	public final String getExtension() {
		return props.getProperty("extension", "");
	}
	
	public final String FindCommand(String cmd) {
		String pathcomp[] = System.getenv("PATH").split(File.pathSeparator);
		for(String p : pathcomp) {
			if(new File(p+File.separator+cmd+getExtension()).exists())
				return p;
		}
		return new String();
	}

	public abstract void shutdown();
	public abstract void reboot();
	
	public abstract String[] getServices();
	public abstract Service getService(String service);
	
	public Map<String,Service> getMapOfServices() {
		Map<String,Service> result = new TreeMap<String,Service>();
		for(String name : getServices())
			result.put(name, getService(name));
		return result;
	}
}
